package com.tj.collection.config;

import com.alibaba.druid.pool.DruidDataSource;
import org.apache.commons.lang.ArrayUtils;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;

import java.io.IOException;

/**
 * Created with IntelliJ IDEA.
 * User: sm
 * Date: 2017/7/10
 * Time: 上午10:26
 */
@Configuration
public class SessionFactoryConfig {
    private String MYBATIS_CONFIG = "mybatis-config.xml";
    /**
     * mybatis mapper resource 路径
     */
    private String MAPPER_PATH = "com/tj/collection/db/mapper/**/*.xml";

    /**
     * id
     */
    private String ID_CENTER_MAPPER_PATH = "com/fqgj/id/sequence/mapper/*.xml";

    @Autowired
    private DruidDataSource dataSource;


    /**
     * 创建sqlSessionFactoryBean 实例
     * 并且设置configtion 如驼峰命名.等等
     * 设置mapper 映射路径
     * 设置datasource数据源
     *
     * @return
     */
    @Bean(name = "sqlSessionFactory")
    public SqlSessionFactoryBean createSqlSessionFactoryBean() throws IOException {
        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
        sqlSessionFactoryBean.setDataSource(dataSource);
        /** 设置mybatis configuration 扫描路径 */
        sqlSessionFactoryBean.setConfigLocation(new ClassPathResource(MYBATIS_CONFIG));

        /** 添加mapper 扫描路径 */
        PathMatchingResourcePatternResolver pathMatchingResourcePatternResolver = new PathMatchingResourcePatternResolver();
        String packageSearchPath = ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX + MAPPER_PATH;
        Resource[] tradeResources = pathMatchingResourcePatternResolver.getResources(packageSearchPath);

        String packageIdPath = ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX + ID_CENTER_MAPPER_PATH;
        Resource[] idSource = pathMatchingResourcePatternResolver.getResources(packageIdPath);

        Resource[] resources = (Resource[]) ArrayUtils.addAll(idSource, tradeResources);

        sqlSessionFactoryBean.setMapperLocations(resources);

        return sqlSessionFactoryBean;
    }


}

